<?php

namespace App\Repositories;

use App\Lib\ApiResponse;
use App\Models\Report;
use App\Models\Setting;
use Facade\FlareClient\Api;
use GuzzleHttp\Client;

class FootWorkRepository
{
    const DETAIL_BASE_URL = 'https://fwlab.xiaoaitech.com/report/report_x5';
    const CALLBACK_URL = 'https://fwlab.xiaoaitech.com/api.php/qrcode/scan_qcode_callback';

    public function getWxMapQrcode($mall_id=0)
    {
        $puid = request()->input('puid');
        $rid = request()->input('rid');
        if(empty($puid) || empty($rid)){
            return ApiResponse::fail('参数错误');
        }

        $setting = Setting::query()->where('mall_id', $mall_id)->first();
        if(empty($setting)){
            return ApiResponse::fail('配置不存在');
        }
        if($puid != $setting->foot_puid){
            return ApiResponse::fail('合作编码不匹配');
        }

        $key = WxMapRepository::FOOT_WORK_STR.':'.$rid;
        $result = (new WxMapRepository())->getWxMapQrcode($key,$mall_id);

        if($result['status'] != ApiResponse::CODE_SUCCESS){
            return $result;
        }

        Report::firstOrCreate([
            'foot_puid' => $puid,
            'foot_rid' => $rid
        ],[
            'wx_ticket' => $result['data']['ticket'],
            'mall_id' => empty($mall_id)?1:$mall_id,
        ]);

        //芯迈固定格式
        return response()->json(['code' => 0, 'url' => $result['data']['full_url'], 'msg' => 'success']);
    }

    public static function getShowDetailUrl($id,$puid,$lg='zh')
    {
        return self::DETAIL_BASE_URL."?id={$id}&puid={$puid}&lg={$lg}";
    }

    protected $client;
    public function syncTofwlab($data = [])
    {
        $limit = 1000;
        $max_id = 0;
        $this->client = new Client([
            'timeout' => 5,
        ]);
        if(isset($data['id'])){
            $report = Report::query()->find($data['id']);
            if(empty($report)) return ApiResponse::fail('报告不存在');
            return $this->doSync($report);
        }

        $ret_data = ['success' => 0, 'fail' => 0];

        while (true){
            $list = Report::query()->where('id','>',$max_id)
                ->where('sync_status',0)
                ->where('sync_lock',0)
                ->orderBy('id','asc')
                ->limit($limit)
                ->get();

            foreach ($list as $report){
                $max_id = $report->id;
                $ret = $this->doSync($report);
                if($ret['status'] == ApiResponse::CODE_SUCCESS){
                    $ret_data['success'] += 1;
                }else{
                    $ret_data['fail'] += 1;
                }
            }
            if(empty($list) || $list->count() < $limit){
                break;
            }
        }

        return ApiResponse::success($ret_data);
    }

    protected function doSync($report)
    {
        $result = $this->client->post(self::CALLBACK_URL,[
            'form_params' => [
                'puid' => $report->foot_puid,
                'rid' => $report->foot_rid,
                'openid' => $report->wx_openid,
            ],
        ]);
        $ret = $result->getBody()->getContents();
        if(strpos($ret, 'ok') !== false){
            $success = true;
            $report->sync_status = 1;
        }else{
            $report->sync_status = -1;
            $report->sync_msg = json_encode($ret);
            $success = false;
        }
        $report->save();
        if($success){
            return ApiResponse::success();
        }
        return ApiResponse::fail($report->sync_msg);
    }
}
